﻿using RightControl.Common;
using RightControl.IService;
using RightControl.Model;
using RightControl.WebApp.Areas.Admin.Controllers;
using System;
using System.Web.Mvc;
using AlibabaCollector;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.IO;
using System.Reflection;

namespace RightControl.WebApp.Areas.DataSrv.Controllers {
    public class SubProductController : BaseController {
        public static IProductService productService { get; set; }
        public static IProductImgService productImgService { get; set; }
        public static ITranslationService translationService { get; set; }
        public static ISubProductService subProductService { get; set; }
        public static IExportFieldsService exportFieldsService { get; set; }
        public static ISubProductImageService subProductImageService { get; set; }
        public static ISubProductSizeService subProductSizeService { get; set; }

        public SubProductController() {

        }

        public ActionResult Index(int id) {


            //ViewData["BaseCategory"] = baseCategoryService.GetAllCategory();
            //base.Index(id);
            return View();
        }

        /// <summary>
        /// 加载数据列表
        /// </summary>
        /// <param name="filter"></param>
        /// <param name="pageInfo"></param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult List(PageInfo pageInfo, ProductDetail filter) {

            return Json(null, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public JsonResult GetAllSubProductImages(int productId) {
            SubProductImage subProdImage = new SubProductImage(productId);
            var result = subProductImageService.GetListByFilter(subProdImage, new PageInfo(1, 100));

            return Json(result, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult UpdateSubProductImages(int seqId, string imgUrls) {
            AjaxResult result = new AjaxResult();
            if (!String.IsNullOrEmpty(imgUrls)) {
                StringBuilder fieldSb = new StringBuilder();
                var imageArray = imgUrls.Split('^'); int idx = 0;
                SubProductImage subProdImage = new SubProductImage();
                subProdImage.Id = seqId;
                PropertyInfo[] pros = subProdImage.GetType().GetProperties();
                for (int i = 0; i < pros.Length; i++) {
                    if (pros[i].Name.StartsWith("Image")) {
                        pros[i].SetValue(subProdImage, imageArray[idx++]);
                        if (fieldSb.Length > 0) {
                            fieldSb.Append(",");
                        }
                        fieldSb.Append(pros[i].Name);
                    }
                    if (idx >= imageArray.Length) break;
                }

                //subProductImageService.UpdateModel(subProdImage);
                //int updCnt = productImgService.SaveImages(imageList);
                result = subProductImageService.UpdateModel(subProdImage, fieldSb.ToString()) ? SuccessTip("已更新成功!") : ErrorTip("更新失败!");

            }
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult UpdateSubProductColor(List<SubProductImage> subProdImgList, int isEng) {
            AjaxResult result = new AjaxResult();

            if (subProdImgList != null) {
                Boolean checkRet = true;
                if (isEng == 1) {
                    foreach (var item in subProdImgList) {
                        if (HtmlUtils.ContainChinese(item.Color)) {
                            result = ErrorTip("变体颜色不能有中文!");
                            checkRet = false;
                            break;
                        }
                    }
                }
                if (checkRet) {
                    result = subProductImageService.UpdateSubProducts(subProdImgList, "Color") >= 0 ? SuccessTip("已更新成功!") : ErrorTip("更新失败!");
                }
            }
            return Json(result, JsonRequestBehavior.AllowGet);
        }
        
        [HttpPost]
        public JsonResult UpdateSingleImage(int seqId, string imgUrl, int index) {
            AjaxResult result = new AjaxResult();
            if (!String.IsNullOrEmpty(imgUrl)) {
                StringBuilder fieldSb = new StringBuilder();
                SubProductImage subProdImage = new SubProductImage();
                subProdImage.Id = seqId;
                if (index == 0) {
                    subProdImage.MainImage = imgUrl;
                    fieldSb.Append("MainImage");
                }
                else {
                    string fieldName = "Image0" + index;
                    PropertyInfo[] pros = subProdImage.GetType().GetProperties();
                    for (int i = 0; i < pros.Length; i++) {
                        if (pros[i].Name == fieldName) {
                            pros[i].SetValue(subProdImage, imgUrl);
                            fieldSb.Append(fieldName);
                        }
                    }
                }
                result = subProductImageService.UpdateModel(subProdImage, fieldSb.ToString()) ? SuccessTip("已更新成功!") : ErrorTip("更新失败!");
            }

            return Json(result, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult DeleteColor(int Id) {
            var result = subProductImageService.DeleteModel(Id) ? SuccessTip() : ErrorTip();
            return Json(result);
        }


        [HttpGet]
        public JsonResult GetAllSubProductSizes(int productId, string categoryCode, int isEng) {
            SubProductSize subProdSize = new SubProductSize(productId);
            var result = subProductSizeService.GetListByFilter(subProdSize, new PageInfo(1, 100));
            List<Dictionary<string, string>> subProductSizesResultList = new List<Dictionary<string, string>>();
            if (result != null && result.count > 0) {
                var tableHead = exportFieldsService.GetExportFields(categoryCode, 2);
                Dictionary<string, string> rows, props; string filedName = "";
                foreach (var item in result.data as List<SubProductSize>) {
                    rows = new Dictionary<string, string>();
                    props = SerializerHelper.JsonDeserialized<Dictionary<string, string>>(item.KeyAttributes);
                    props = props == null ? new Dictionary<string, string>() : props;

                    rows["Id"] = item.Id.ToString();
                    rows["OriSize"] = item.OriSize;
                    rows["Size"] = item.Size;
                    rows["Price"] = item.Price.ToString();
                    rows["UpdateOn"] = item.UpdateOn.ToString("yyyy-MM-dd HH:mm");

                    if (props != null) {
                        tableHead.ForEach(h => {
                            filedName = isEng == 1 ? h.EngFieldNm : h.FieldName;
                            rows[filedName] = props.ContainsKey(filedName) ? props[filedName] : "";
                        });
                    }
                    subProductSizesResultList.Add(rows);
                }
            }
            return Json(Pager.Paging(subProductSizesResultList, result.count), JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public JsonResult GetAllSubProducts(int productId, string categoryCode) {
            SubProduct subProduct = new SubProduct() { ProductId = productId };
            var result = subProductService.GetListByFilter(subProduct, new PageInfo(1, 100));
            List<Dictionary<string, string>> subProductResultList = new List<Dictionary<string, string>>();
            if (result != null && result.count > 0) {
                var tableHead = exportFieldsService.GetExportFields(categoryCode, 2);
                Dictionary<string, string> rows, props;
                foreach (var item in result.data as List<SubProduct>) {
                    rows = new Dictionary<string, string>();
                    props = SerializerHelper.JsonDeserialized<Dictionary<string, string>>(item.KeyAttributes);
                    props = props == null ? new Dictionary<string, string>() : props;
                    rows["Id"] = item.Id.ToString();
                    rows["ImageUrl"] = item.ImageUrl;
                    rows["Color"] = item.Color;
                    rows["SkuId"] = item.SkuId;
                    rows["Size"] = item.Size;
                    rows["UpdateOn"] = item.UpdateOn.ToString("yyyy-MM-dd HH:mm");

                    if (props != null) {
                        tableHead.ForEach(h => {
                            rows[h.FieldName] = props.ContainsKey(h.FieldName) ? props[h.FieldName] : "";
                        });
                    }
                    subProductResultList.Add(rows);
                }
            }

            return Json(Pager.Paging(subProductResultList, result.count), JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult UpdateSubProductSizes(string categoryCode, List<SubProductSize> subProdSizeList,int isEng) {
            AjaxResult result = new AjaxResult();
            if (subProdSizeList.IsNotEmpty()) {
                Dictionary<string, string> propsOfSize = new Dictionary<string, string>();
                var keyFields = exportFieldsService.GetExportFields(categoryCode, 2);
                subProdSizeList.ForEach(p => {
                    p.CreateOn = DateTime.Now;
                    p.UpdateBy = Operator.UserId;

                    if (propsOfSize.ContainsKey(p.Size)) {
                        p.KeyAttributes = propsOfSize[p.Size];
                    }
                    else {
                        string[] keyArrtributes = p.KeyAttributes.Split('^');
                        if (keyArrtributes != null && keyArrtributes.Length > 0) {
                            Dictionary<string, string> props = new Dictionary<string, string>(); int idx = 0;
                            foreach (var item in keyArrtributes) {
                                if (isEng == 1) {
                                    props[keyFields[idx++].EngFieldNm] = item;
                                }
                                else {
                                    props[keyFields[idx++].FieldName] = item;
                                }
                            }
                            p.KeyAttributes = SerializerHelper.JsonSerialized<Dictionary<string, string>>(props);
                            propsOfSize[p.Size] = p.KeyAttributes;
                        }
                    }
                });

                result = subProductSizeService.UpdateSubProductSizes(subProdSizeList, "Size,KeyAttributes") ? SuccessTip("已成功更新!") : ErrorTip("更新失败!");
            }
            else {
                result = SuccessTip("已更新成功!");
            }

            return Json(result, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult DeleteSize(int Id) {
            var result = subProductSizeService.DeleteModel(Id) ? SuccessTip() : ErrorTip();
            return Json(result);
        }

        [HttpPost]
        public ActionResult DelProductImages(int Id) {
            var result = productImgService.DeleteModel(Id) ? SuccessTip() : ErrorTip();
            return Json(result);
        }

        [HttpPost]
        public JsonResult UpdateImgType(ProductImage prodImage) {
            AjaxResult result = new AjaxResult();
            if (prodImage != null) {
                result = productImgService.UpdateModel(prodImage, "ImgType") ? SuccessTip() : ErrorTip("更新失败,请稍后重试!");
            }
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult UpdateImagesSort(string mainImgIds,string dImgIds) {
            AjaxResult result = new AjaxResult();
            if (!String.IsNullOrEmpty(mainImgIds) || !String.IsNullOrEmpty(dImgIds)) {              
                List<ProductImage> imageList = new List<ProductImage>();
                string[] imgArray = mainImgIds.Split('^');
                for (int i = 0; i < imgArray.Length; i++) {
                    imageList.Add(new ProductImage(imgArray[i].ToInt(), i + 1));
                }

                imgArray = dImgIds.Split('^');
                for (int i = 0; i < imgArray.Length; i++) {
                    imageList.Add(new ProductImage(imgArray[i].ToInt(), i + 1));
                }
                int upCnt = productImgService.UpdateProductImgSort(imageList);
                result = upCnt > 0 ? SuccessTip(string.Format("已成功更新{0}张图片!", upCnt)) : ErrorTip("更新失败!");
            }
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult UpdateImages(int productId, string mainImgUrls, string dImgUrls) {
            AjaxResult result = new AjaxResult();
            if (!String.IsNullOrEmpty(mainImgUrls) || !String.IsNullOrEmpty(dImgUrls)) {
                if (productImgService.DeleteByProdcutId(productId, Operator.UserId)) {
                    List<ProductImage> imageList = new List<ProductImage>();
                    string[] imgArray = mainImgUrls.Split('^');
                    for (int i = 0; i < imgArray.Length; i++) {
                        imageList.Add(new ProductImage(productId, imgArray[i], 1, Operator.UserId, i+1));
                    }
                    
                    imgArray =dImgUrls.Split('^');
                    for (int i = 0; i < imgArray.Length; i++) {
                        imageList.Add(new ProductImage(productId, imgArray[i], 2, Operator.UserId, i + 1));
                    }
                    int updCnt = productImgService.SaveImages(imageList);
                    result = updCnt > 0 ? SuccessTip(string.Format("已成功更新{0}张图片!", updCnt)) : ErrorTip("更新失败!");
                }
            }
            else {
                result = SuccessTip("已更新成功!");
            }
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        //public ActionResult Detail(int Id) {
        //    var model = productService.GetDetail(Id);
        //    return View(model);
        //}
        public ActionResult Edit(int Id, int isEng) {
            var model = productService.ReadModel(Id);
            if (model != null) {
                ViewData["TableHead"] = exportFieldsService.GetExportFields(model.CategoryCode, 2);
                dynamic imagsRet = productImgService.GetListByFilter(new ProductImage(Id), new PageInfo(1, 10000));
                if (imagsRet != null && imagsRet.code == 0) {
                    ViewData["productImgs"] = imagsRet.data;
                }
            }
            ViewData["Size"] = isEng == 1 ? "Size" : "尺寸";
            ViewData["IsEng"] = isEng;
            return View(model);
        }

        private static void TranslateDetails(ProductDetail model) {

            StringBuilder sb = new StringBuilder();
            Dictionary<string, string> translatedResult = new Dictionary<string, string>();
            Dictionary<string, string> description = SerializerHelper.JsonDeserialized<Dictionary<string, string>>(model.Description);
            foreach (var item in description) {
                sb.AppendFormat("'{0}','{1}',", item.Key, item.Value);
            }
            Translation trans = new Translation();
            trans.OriContent = sb.ToString().TrimEnd(',');
            dynamic result = translationService.GetListByFilter(trans, new PageInfo(1, 10000));

            if (result != null && result.code == 0) {
                Dictionary<string, string> translateDic = new Dictionary<string, string>();
                for (int i = 0; i < result.count; i++) {
                    translateDic[result.data[i].OriContent] = result.data[i].TransEnglish;
                }
                String tmpVal = "";
                foreach (var item in description) {
                    tmpVal = translateDic.ContainsKey(item.Key) ? translateDic[item.Key] : item.Key;
                    translatedResult[tmpVal] = translateDic.ContainsKey(item.Value) ? translateDic[item.Value] : item.Value;
                }
            }

            //return Json(translatedResult, JsonRequestBehavior.AllowGet); 
        }
        
        /// <summary>
        /// 删除按钮
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Delete(int Id) {
            //删除权限时,同时删除菜单权限,菜单角色权限记录
            Boolean delMode = productService.DeleteModel(Id);
            Boolean deImg = productImgService.DeleteByProdcutId(Id, Operator.UserId, 2);
            Boolean deSubProduct = subProductService.DeleteByProdcutId(Id);
            var result = delMode && deImg && deSubProduct ? SuccessTip() : ErrorTip();
            return Json(result);
        }

    }
}